<?php
class Admin_EnquireController extends Apps_Controller_Action {
	public function indexAction() {
		$this->_redirect('/admin/enquire/list-enquire');
	}

	public function listEnquireAction() {
		//  Action Delete
			$this->actResolve('act_delete',
					'delete', null, null, array('id' => $this->_getParam('item_checker')),
					true);

		$tbEnquire = new M_DbTable_Enquire();
		$grid = new Apps_Plugin_Grid('EnquireGrid');
		// Set Grid
		$grid->setData($tbEnquire->getList())
			 ->setTableCaption('List Enquire')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'width'		=> '1%',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Customer',
			 			  'dataField'	=> 'full_name'),
			 		array('title'		=> 'Email',
			 			  'html'        => array('<a href="mailto:%s" target="_blank">%s</a>',
			 			  				  array('email', 'email')),),
			 		array('title'		=> 'Title',
			 			  'html'        => array('<input type="text" class="input-v" value="%s">',
			 			  				   array('subject')),),
			 		array('title'		=> 'Content',
			 			  'html'        => function($rs) {
			 			                        $l = 100;
		                                        return "<input type='text' class='input-v' value='". ((strlen($rs['message']) > $l)? substr($rs['message'], 0, $l).'...' : $rs['message']) ."' >";
			 			  }),
			 		array('title'		=> 'About',
	                      'html'        => function($rs) {
	                                            $labelEnquireReferenceType = new Apps_View_Helper_LabelEnquireReferenceType();
	                                            return $labelEnquireReferenceType->labelEnquiresReferenceType($rs['reference_type']);
	                                        }),
			 		array('title'		=> 'Reference To',
			 			  'html'		=> function($rs) {
			 			                         $tbEnquire = new M_DbTable_Enquire();
	 			                                 $tbArticle = new M_DbTable_Article();

			 			                         switch ($rs['reference_type']) {
			 			                             case $tbEnquire::REFERENCE_TYPE_TOUR :
			 			                                 $article = $tbArticle->fetchRow(array('reference_id =?' => $rs['reference_id'], 'reference_type =?' => $tbArticle::REFERENCE_TYPE_TOUR));
			 			                                 $link    = '<a target="_blank" href="/tour/detail?id='. $rs['reference_id'] .'">'. $article['en_title'] .'</a>';
			 			                             break;
			 			                             case $tbEnquire::REFERENCE_TYPE_CRUISE :
			 			                                 $article = $tbArticle->fetchRow(array('reference_id =?' => $rs['reference_id'], 'reference_type =?' => $tbArticle::REFERENCE_TYPE_CRUISE));
			 			                                 $link    = '<a target="_blank" href="/cruise/detail?id='. $rs['reference_id'] .'">'. $article['en_title'] .'</a>';
			 			                             break;
			 			                             case $tbEnquire::REFERENCE_TYPE_HOTEL :
			 			                                 $article = $tbArticle->fetchRow(array('reference_id =?' => $rs['reference_id'], 'reference_type =?' => $tbArticle::REFERENCE_TYPE_HOTEL));
			 			                                 $link    = '<a target="_blank" href="/hotel/detail?id='. $rs['reference_id'] .'">'. $article['en_title'] .'</a>';
			 			                             break;
			 			                             case $tbEnquire::REFERENCE_TYPE_NOT_DEFINE :
			 			                                 $link = "";
			 			                             break;
			 			                         }
			 			                         return $link;
			 			  					}),
                    array('title'		=> 'Status',
			 			  'width'		=> '7%',
                            'html'	    => function ($rs) {
                                                return ($rs['status'] == M_DbTable_Enquire::STATUS_ACTIVE)?
                                                '<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/enquire/change-value?p=status&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Checked">New</a>' :
                                                '<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/enquire/change-value?p=status&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="New">Checked</a>';
                                        },
                          'class'		=> 'center'),
			 		array('title'		=> 'Save Customer',
			 			  'width'		=> '4%',
			 			  'class'		=> 'center',
			 			  'html'		=> function($rs) {
			 			  						return $rs['customer_id'] ?
			 			  							"Đã lưu" :
			 			  						   '&nbsp&nbsp&nbsp<a class="ajax-link popup"
									        	   data-ajax-to="/admin/enquire/save-customer?id=' .$rs['id']. '&&cu=' .$rs['full_name']. '&&e=' .$rs['email']. '&&p=' .$rs['phone']. '&&c=' .$rs['country_residence']. '&&d=' .$rs['message']. '"
									        	   data-ajax-elem="#modal-box"
									        	   data-toggle="modal"
									        	   data-target="#modal-box"
									        	   href="##"><i class="icon-plus" title="Lưu thông tin khách hàng"></i></a>';
			 			  }),
			 		array('title'		=> 'Save Order',
			 			  'width'		=> '4%',
			 			  'class'		=> 'center',
			 			  'html'       	=> function($rs) {
			 			  						return $rs['customer_id'] ?
			 			  							'<a class="ajax-link popup"
									        	   data-ajax-to="/admin/enquire/save-order?id=' .$rs['id']. '&&d='. $rs['message']. '&&customer_id='. $rs['customer_id'] .'"
									        	   data-ajax-elem="#modal-box"
									        	   data-toggle="modal"
									        	   data-target="#modal-box"
									        	   href="##"><i class="icon-plus" title="Thêm thông tin đặt hàng"></i></a>' :
			 			  							'<a class="ajax-link popup"
									        	   data-ajax-to="/admin/enquire/save?id=' .$rs['id']. '&&cu=' .$rs['full_name']. '&&e=' .$rs['email']. '&&p=' .$rs['phone']. '&&c=' .$rs['country_residence']. '&&d=' .$rs['message']. '"
									        	   data-ajax-elem="#modal-box"
									        	   data-toggle="modal"
									        	   data-target="#modal-box"
									        	   href="##"><i class="icon-plus" title="Lưu thông tin khách hàng và chi tiết đặt hàng"></i></a>';
											}),
			 		array('title'		=> 'View',
			 			  'html'        => array('<a href="/admin/enquire/detail?id=%s"><i class="icon-list-alt"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center'),
			 		array('title'      	=> 'Delete',
			 			  'html'       	=> array('<a href="/admin/enquire/delete?id=%s"><i class="icon-remove must-confirm " title="Xóa"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center',
			 			  'width'      	=> '1%')
			 		));
		$grid->applySearch(new Admin_Form_Search_Enquire());

		$this->view->grid = $grid;
	}

	public function detailAction() {
		$rq = $this->getRequest();
		$enquireId = intval($rq->getParam('id'));
		$tbEnquire = new M_DbTable_Enquire();
		$enquire = $tbEnquire->getEnquireyById($enquireId)->query()->fetch();

		$this->view->enquire = $enquire;
	}


	public function deleteAction() {
		$this->disableLayout(true, true);

		$rq = $this->_request;
		$EnquireIds = $rq->getParam('id');
		$tbEnquire = new M_DbTable_Enquire();

		if(is_numeric($EnquireIds)) {
			$this->_flashMessenger->addMessage(
						$tbEnquire->safelyDelete(array('id = ?' => $EnquireIds)) ?
						self::$msgDeleteSuccess :
						self::$msgDeleteError
					);
			$this->goToActionIndex();
		} elseif (is_array($EnquireIds)) {
			foreach ($EnquireIds as $enquireId) {
				$tbEnquire->safelyDelete(array('id = ?' => $enquireId));
			}
			$this->_flashMessenger->addMessage(self::$msgDeleteSuccess);
			$this->goToActionIndex();
		} else {
			$this->_flashMessenger->addMessage(self::$msgNoRecordFound);
			$this->goToActionIndex();
		}
	}
/*
	public function changeValueAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$param  = $rq->getParam('p');
		$id 	= intval($rq->getParam('id'));
		$tbEnquire = new M_DbTable_Enquire();
		if(!($r = $tbEnquire->fetchRow(array('id = ?' => $id))->toArray())) {
			echo '<script>window.location=window.location</script>
				<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
				. $this->getBacktrackUrl()
				. '">Update Error (Record not found), please wait ...</a>';
		}

		switch ($param) {
			case 'status':
				($r['status'] == M_DbTable_Enquire::STATUS_ACTIVE) ?
					$tbEnquire->safelyUpdate(array('status' 		=> M_DbTable_Enquire::STATUS_INACTIVE),
										     array('status = ?' 	=> M_DbTable_Enquire::STATUS_ACTIVE,
										   		   'id =?'			=> $id)) :
					$tbEnquire->safelyUpdate(array('status' 		=> M_DbTable_Enquire::STATUS_ACTIVE),
										     array('status = ?' 	=> M_DbTable_Enquire::STATUS_INACTIVE,
										   		   'id =?'			=> $id));
				break;


			default: break;
		}

	}
 */
	public function saveAction() {
    	$this->disableLayout(true, false);
    	$rq = $this->_request;
        $tbOrder = new M_DbTable_Order();
        $tbCustomer = new M_DbTable_Customer();
		$tbEnquire = new M_DbTable_Enquire();
		$tbOrderStatus = new M_DbTable_OrderStatus();
		$tbPaymentType = new M_DbTable_PaymentType();

        $enquireId = $this->_getParam('id');
        if(null === $enquireId) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
                // Send Refresh JS
                echo '<script>window.location=window.location</script>
                <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                , $this->getBacktrackUrl()
                , '">Update successfully, please wait ...</a>';
        }

        if(!($o = $tbOrderStatus->fetchAll()->toArray()) || !($p = $tbPaymentType->fetchAll()->toArray())) {
        	$this->_flashMessenger->addMessage('Phải thêm Kiểu mua hàng và kiểu thanh toán trước');
	        	// Send Refresh JS
	        	echo '<script>window.location=window.location</script>
	        	<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
	        	, $this->getBacktrackUrl()
	        	, '">Update successfully, please wait ...</a>';
        }

 		$f = new Admin_Form_AddCustomerAndOrder();

        $dataPopulate = array();
        $dataPopulate['full_name'] 			= $rq->getParam('cu');
        $dataPopulate['email'] 				= $rq->getParam('e');
        $dataPopulate['phone'] 				= $rq->getParam('p');
        $dataPopulate['country_residence'] 	= $rq->getParam('c');
        $dataPopulate['description'] 		= $rq->getParam('d');

        if($rq->isPost()) {
            if($f->isValid($rq->getParams())) {

                $data = array();
                $data = $f->getValues();

                $r = $tbCustomer->safelyInsert($data);
                if($r) {
                	$tbEnquire->safelyUpdate(array('customer_id' => $r,
                								   'reference_id' => $data['reference_id'],
                								   'reference_type' => $data['reference_type']
                							 ),
                							 array('id = ?' => $enquireId));
	                // Remove Description of Customer and add Description of Order
	                $data['description'] = $data['description-order'];
	                // Add Customer Id
	                $data['customer_id'] = $r;
	                $r = $r && $tbOrder->safelyInsert($data);
                }
                $this->_flashMessenger->addMessage($r ? self::$msgAddSuccess : self::$msgAddFailed);
                // Send Refresh JS
                echo '<script>window.location=window.location</script>
                <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                , $this->getBacktrackUrl()
                , '">Update successfully, please wait ...</a>';

            }
        } else{
        	$f->populate($dataPopulate);
        }

        $this->view->form = $f;
	}
	public function saveCustomerAction() {
    	$this->disableLayout(true, false);
    	$rq = $this->_request;

        $enquireId = $this->_getParam('id');
        if(null == $enquireId) {
        	// Send Refresh JS
        	echo '<script>window.location=window.location</script>
        	<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
        	, $this->getBacktrackUrl()
        	, '">Update successfully, please wait ...</a>';
        }

        $f = new Admin_Form_AddCustomer();

        $dataPopulate = array();
        $dataPopulate['full_name'] 			= $rq->getParam('cu');
        $dataPopulate['email'] 				= $rq->getParam('e');
        $dataPopulate['phone'] 				= $rq->getParam('p');
        $dataPopulate['country_residence'] 	= $rq->getParam('c');
        $dataPopulate['description'] 		= $rq->getParam('d');

        if($rq->isPost()) {
            if($f->isValid($rq->getParams())) {
                $tbCustomer = new M_DbTable_Customer();
                $tbEnquire = new M_DbTable_Enquire();

                $data = array();
                $data = $f->getValues();
                $r = $tbCustomer->safelyInsert($data);
                if($r) {
	                $r = $tbEnquire->safelyUpdate(array('customer_id' => $r) , array('id = ?' => $enquireId));
                }

                $this->_flashMessenger->addMessage($r ? self::$msgAddSuccess : self::$msgAddFailed);
                // Send Refresh JS
                echo '<script>window.location=window.location</script>
                <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                , $this->getBacktrackUrl()
                , '">Update successfully, please wait ...</a>';

            }
        } else{
        	$f->populate($dataPopulate);
        }

        $this->view->form = $f;
	}
	public function saveOrderAction() {
    	$this->disableLayout(true, false);
    	$rq = $this->_request;

        $enquireId = $this->_getParam('id');
        $customerId = $rq->getParam('customer_id');

		$tbOrderStatus = new M_DbTable_OrderStatus();
		$tbPaymentType = new M_DbTable_PaymentType();
        if(!($o = $tbOrderStatus->fetchAll()->toArray()) || !($p = $tbPaymentType->fetchAll()->toArray())) {
        	$this->_flashMessenger->addMessage('Phải thêm Kiểu mua hàng và kiểu thanh toán trước');
        	// Send Refresh JS
        	echo '<script>window.location=window.location</script>
        	<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
        	, $this->getBacktrackUrl()
        	, '">Update successfully, please wait ...</a>';
        }

        if(null === $enquireId || null == $customerId) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
        	// Send Refresh JS
        	echo '<script>window.location=window.location</script>
        	<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
        	, $this->getBacktrackUrl()
        	, '">Update successfully, please wait ...</a>';
        }

        $f =  new Admin_Form_AddOrder();
        $dataPopulate['description'] = $rq->getParam('d');

        if($rq->isPost()) {
            if($f->isValid($rq->getParams())) {
                $tbOrder 	= new M_DbTable_Order();
                $tbCustomer = new M_DbTable_Customer();
                $tbEnquire 	= new M_DbTable_Enquire();

                $data = array();
                $data = $f->getValues();
                $data['customer_id'] = $customerId;

         		$r = $tbOrder->safelyInsert($data);

         		if($r) {
					$r = $r && $tbEnquire->safelyUpdate(array('status' => M_DbTable_Enquire::STATUS_INACTIVE,
															  'reference_id' => $data['reference_id'],
                								   			  'reference_type' => $data['reference_type']
														),
														array('id = ?' => $enquireId));
         		}

                $this->_flashMessenger->addMessage($r ? self::$msgAddSuccess : self::$msgAddFailed);
                // Send Refresh JS
                echo '<script>window.location=window.location</script>
                <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                , $this->getBacktrackUrl()
                , '">Update successfully, please wait ...</a>';

            }
        } else{
        	$f->populate($dataPopulate);
        }

        $this->view->form = $f;
	}

	public function changeValueAction() {
	    $this->disableLayout(true, true);
	    $rq = $this->_request;
	    $param  = $rq->getParam('p');
	    $id 	= intval($rq->getParam('id'));
	    $tbEnquire = new M_DbTable_Enquire();
	    if(!($r = $tbEnquire->fetchRow(array('id = ?' => $id))->toArray())) {
	        echo '<script>window.location=window.location</script>
	        <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
	        . $this->getBacktrackUrl()
	        . '">Update Error (Record not found), please wait ...</a>';
	    }

	    switch ($param) {
	        case 'status':
	            ($r['status'] == M_DbTable_Enquire::STATUS_ACTIVE)
	            ? $tbEnquire->safelyUpdate(array('status'  => M_DbTable_Enquire::STATUS_INACTIVE), //unchecked
	                                       array('id =?'	  => $id))
                : $tbEnquire->safelyUpdate(array('status'  => M_DbTable_Enquire::STATUS_ACTIVE), //checked
	                                       array('id =?'  => $id));
	            break;
	        default: break;
	    }

	    echo '<script>location.href = location.href</script>
        	    <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
        	    . $this->getBacktrackUrl()
        	    . '">Update successfully, please wait ...</a>';
	}
}